package com.wm.ad_navi_new.skin.util

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import androidx.core.content.ContextCompat
import com.wm.ad_navi_new.MyApplication
import com.wm.ad_navi_new.skin.SkinManager

object SkinResourcesUtil {

    /**
     * 获取对应的颜色
     */
    @SuppressLint("DiscouragedApi")
    fun getColor(resId: Int): Int {
        val context: Context = MyApplication.context
        val originColor = ContextCompat.getColor(context, resId)
        if (SkinManager.isCurrentDefaultSkin()) {
            return originColor
        }
        val resName: String = getResourceEntryNameById(resId)
        val trueResId = context.resources.getIdentifier(resName, "color", context.packageName)
        val trueColor: Int = if (trueResId == 0) {
            originColor
        } else {
            context.resources.getColor(trueResId)
        }
        return trueColor
    }

    fun getDrawable(resId: Int): Drawable? {
        val context: Context = MyApplication.context ?: return null
        val originDrawable = ContextCompat.getDrawable(context, resId)
        if (SkinManager.isCurrentDefaultSkin()) {
            return originDrawable
        }
        val resName: String? = getResourceEntryNameById(resId)
        var trueResId = context.resources.getIdentifier(resName, "drawable", context.packageName)
        val trueDrawable: Drawable?
        if (trueResId == 0) {
            trueResId = context.resources.getIdentifier(resName, "mipmap", context.packageName)
        }
        trueDrawable = if (trueResId == 0) {
            originDrawable
        } else {
            if (Build.VERSION.SDK_INT < 22) {
                context.resources.getDrawable(trueResId)
            } else {
                context.resources.getDrawable(trueResId, null)
            }
        }
        return trueDrawable
    }

    /**
     * 将对应的字段进行拼接
     */
    private fun getResourceEntryNameById(resId: Int): String {
        val resourceEntryName: String = MyApplication.context.resources.getResourceEntryName(resId)
        return SkinManager.wrapper(resourceEntryName)
    }

}